import configparser


class PubSubTopic():
    def __init__(self):
        self.ser = ''
        self.log = ''

    def psPostTopic(self, key, data):
        try:
            conf = configparser.ConfigParser()
            conf.read('./TopicParams.ini', encoding="utf-8")
            value = conf.get('TopicParams', key)

            setTopicResult = self.ser.PubSub(data=f'AT+{key.upper()}={value}')
            self.log.tempFileLog(f'设置topic：AT+{key.upper()}={value}并订阅{setTopicResult}')

            method = '\"thing.event.property.post\"'
            methodResult = self.ser.PubSub(data=f'AT+METHOD={method}')
            self.log.tempFileLog(f'发布method内容：AT+METHOD={method}并订阅{methodResult}')

            dkey, dvalue = list(data.items())[0]

            keyResult = self.ser.PubSub(data=f'AT+POSTIDENTIFIER=\"{dkey}\"')
            self.log.tempFileLog(f'发布key内容：AT+POSTIDENTIFIER=\"{dkey}\"并订阅{keyResult}')

            valueResult = self.ser.PubSub(data=f'AT+POSTVALUE={dvalue}')
            self.log.tempFileLog(f'发布key内容：AT+POSTVALUE={dvalue}并订阅{valueResult}')

            psResult = self.ser.PubSub(data=f'AT+POST')
            self.log.tempFileLog(f'发布提交内容：AT+POST并订阅{psResult}')

            self.log.runFileLog(f'发送topic成功')
        except Exception as e:
            self.log.exceptFileLog(f'发送topic出错，错误原因：{e}')

    def main(self):
        self.psPostTopic('posttopics', {'CurrentTemperature': 15})


if __name__ == '__main__':
    from runTimeLogUiUtil import *
    app = QtWidgets.QApplication(sys.argv)
    from serialUtil import *
    ser = SerialUtil(port='COM6', bps=115200, timeout=0.5)
    log = RunTimeLogUiUtil()
    ps = PubSubTopic()
    ps.ser = ser
    ps.log = log
    ps.psPostTopic('eventopicslight', {'CurrentTemperature': 15})
    sys.exit(app.exec_())